package com.wufeng.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wufeng.dto.ArticleUserDto;
import com.wufeng.dto.R;
import com.wufeng.entity.Article;
import com.wufeng.entity.ArticleLikeRecord;
import com.wufeng.entity.Reply;
import com.wufeng.service.ArticleLikeRecordService;
import com.wufeng.service.ArticleService;
import com.wufeng.service.ReplyService;
import com.wufeng.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章表(Article)表控制层
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ReplyService replyService;

    @Autowired
    private ArticleLikeRecordService articleLikeRecordService;


    /**
     * 增加一个文章
     */
    @PostMapping("/addArticle")
    public R addArticle(@RequestBody Article article) {
        boolean isSaved = articleService.save(article);
        Map<String, Object> map = new HashMap<>();

        if (isSaved) {
            map.put("saved", true);
            map.put("msg", "提交成功");
        } else {
            map.put("saved", false);
            map.put("msg", "提交失败");
        }
        return R.ok(map);
    }

    /**
     * 获得文章分页数据
     *
     * @return
     */
    @PostMapping("/articleListByPage")
    public R articleListByPage(@RequestBody Map<String, Object> param) {
        Integer pageIndex = Integer.parseInt(param.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(param.get("pageSize").toString());
        Page<Article> page = articleService.page(new Page<Article>(pageIndex, pageSize));
        PageUtils pageUtils = new PageUtils(page);
        Map<String, Object> map = new HashMap<>();
        map.put("list", pageUtils.getList());
        map.put("totalPage", pageUtils.getTotalPage());
        map.put("countTotal", pageUtils.getTotalCount());

        return R.ok(map);
    }

    /**
     * 根据文章id获取文章信息
     *
     * @param articleId
     * @return
     */
    @GetMapping("/getArticleById")
    public R getArticleById(@RequestParam Integer articleId) {
        Article article = articleService.getById(articleId);
        Map<String, Object> map = new HashMap<>();
        map.put("article", article);
        return R.ok(map);
    }

    /**
     * 根据文章id删除文章，同时，删除评论，删除点赞记录
     *
     * @param articleId
     * @return
     */
    @Transactional
    @PostMapping("/deleteArticleById")
    public R deleteArticleById(@RequestParam("articleId") Integer articleId) {

        //1.删除评论
        QueryWrapper<Reply> wrapper = new QueryWrapper<>();
        wrapper.eq("articleId", articleId);
        boolean deleteReply = replyService.remove(wrapper);


        //删除点赞记录
        boolean isDelete = articleLikeRecordService.remove(
                new QueryWrapper<ArticleLikeRecord>().eq("articleId", articleId));

        //2.删除文章(最后删除)
        boolean deleteArticle = articleService.removeById(articleId);

        Map<String, Object> map = new HashMap<>();
        map.put("isDelete", deleteArticle && isDelete && deleteReply);

        return R.ok(map);
    }

    /**
     * 根据用户id获取文章列表
     *
     * @param userId
     * @return
     */
    @GetMapping("/getArticleListByUserId")
    public R getArticleListByUserId(@RequestParam("userId") Integer userId) {
        List<Article> articleList = articleService.list(new QueryWrapper<Article>().eq("userId", userId).orderByDesc("createTime"));

        Map<String, Object> map = new HashMap<>();
        map.put("list", articleList);
        return R.ok(map);
    }


    @GetMapping("/getArticleLikeCountById")
    public R getArticleLikeCountByUserId(@RequestParam("userId") Integer userId) {
        //查出用户所有文章
        List<Article> articles = articleService.list(new QueryWrapper<Article>().eq("userId", userId));

        //遍历求点赞和
        int likeCount = 0;
        for (Article article : articles) {
            likeCount += article.getLikecount();
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        return R.ok(map);
    }


    /**
     * 根据条件查询出分页文章数据
     *
     * @param params
     * @return
     */
    @PostMapping("/getArticleListByCondition")
    public R getArticleListByCondition(@RequestBody Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        if (pageIndex == null || pageSize == null) {
            pageIndex = 1;
            pageSize = 5;
        }

        Article article = new Article();
        //设置需要查询的信息
        article.setArticletitle((String) params.get("articletitle"));
        article.setArticlecontent((String) params.get("articlecontent"));

        List<ArticleUserDto> articleUserDtoList =
                articleService.getArticleListByCondition(article, pageIndex, pageSize);
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleList", articleUserDtoList);

        return R.ok(map);

    }


    @PostMapping("/getArticleCount")
    public R getArticleCount(@RequestBody Article article) {

        QueryWrapper<Article> qw = new QueryWrapper<Article>();
        if (article.getArticletitle() != null && !article.getArticletitle().equals("")) {
            qw.like("articleTitle", article.getArticletitle());
        }
        if (article.getArticlecontent() != null && !article.getArticlecontent().equals("")) {
            qw.like("articleContent", article.getArticlecontent());
        }

        long count = articleService.count(qw);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", count);
        return R.ok(map);
    }


    @PostMapping("/updateArticleById")
    public R updateArticleById(@RequestBody Article article) {
        try {
            articleService.updateById(article);
        }catch (Exception e){
            return R.error("更新失败！");
        }

        return R.ok("更新成功！");
    }


}
